﻿<?PHP
	header('Content-type: text/xml; charset=UTF-8');	
	
	include_once("classe/class.webapi.php");
	include_once("classe/class.inventorydatabase.php");
	
	$inventoryDatabase = new InventoryDatabase();
	
	$input = file_get_contents("php://input");
	
	if ($input == "") {
		echo "<h1><i>WEBAPI Version 1.0</i></h1>";
		echo "<h3>This page must by call from a webapi request. Please see the documentation of KitchenInventorySDK to use this page</h2>";
		echo "<a href='mailto:david.cuerrier@gmail.com'>david.cuerrier@gmail.com</a>";
		echo "<br/><br/>";
		
		foreach (get_class_methods("InventoryDatabase") as $r) {			
			$method = new ReflectionMethod("InventoryDatabase", $r);
			if ($method->class == "InventoryDatabase") {
				$tmp = $method->name."(";
				$params = $method->getParameters();
				foreach ($params as $param) {
					if ($param->isOptional())
						$tmp .= "[".$param->name." = ".$param->getDefaultValue()."] ";
					else
						$tmp .= $param->name." ";
				}
				$tmp .= ")";
				}
			
				echo "$tmp<br/>";
		}		
			
	} else {
	
		// Result object
		$result = new webAPIResultObject();
	
		// If its a good call, open the DB connection
		$inventoryDatabase->openConnection("./config/config.database.xml");
	
		// Take the XML request and turn it to variable
		$request = new SimpleXMLElement($input);		
		$id = $request->attributes(); $id = $id['id'];		
		$functionName = $request->xpath("/request/function");
		$functionName = (string)$functionName[0];
		$arg = $request->xpath("/request/arguments/argument");
		$argument = Array();
		
		foreach ($arg as $t) {
			$att = $t->attributes();	
			$argument[(string)$att['name']] = '"'.(string)$t.'"';
		}
		
		$result->setID($id);
		$flist = implode(";", get_class_methods("InventoryDatabase"));		
		
		if (strrpos(";".$flist.";", ";".$functionName.";") === false) {
			$result->setState("500");
			$result->addRow(Array("Detail" => "The specified function name ($functionName) is not reconized as a good function."));
		}
		else {
			$result->setState("200");
			
			$argsList = (count($argument) > 0) ? implode(",",$argument) : "";
			
			eval("\$ret = \$inventoryDatabase->$functionName($argsList);");			
			
			if ($ret != null)
				foreach ($ret as $row) { $result->addRow($row); }
			else
				$result->addRow(Array("Detail" => "Your command have be processed with success."));
		}
		
		echo utf8_encode($result->getObject());
		
	}
	
?>